package com.xneure.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xneure.utils.bean.GUID;
import com.xneure.utils.intf.JsonHandler;

public class JsonUtil {
	static List<SerializeFilter> sf = new ArrayList<SerializeFilter>(20);
	public static String DEFAULT_DATE_TIME_FORMAT = DateUtil.DEFAULT_DATE_TIME_FORMAT;
	static {
		JsonHandler guid = new JsonHandler() {
			@Override
			public Object toObject(Object obj, Type type, Object fieldName) {
				return GUID.valueOf(obj.toString());
			}

			@Override
			public String toJson(Object object, Object fieldName, Type fieldType) {
				return object.toString();
			}
		};
		JsonHandler date = new JsonHandler() {
			@Override
			public Object toObject(Object obj, Type type, Object fieldName) {
				return DateUtil.autoFormat(obj.toString());
			}

			@Override
			public String toJson(Object object, Object fieldName, Type fieldType) {
				String dateFormat = DateUtil.dateFormat((Date) object, DEFAULT_DATE_TIME_FORMAT);
				return dateFormat.replace(" 00:00:00", "");
			}
		};
		JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
		SerializeConfig.getGlobalInstance().put(GUID.class, guid);
		ParserConfig.getGlobalInstance().putDeserializer(GUID.class, guid);
		SerializeConfig.getGlobalInstance().put(Date.class, date);
		ParserConfig.getGlobalInstance().putDeserializer(Date.class, date);
	}

	public static void addFilter(SerializeFilter filter) {
		if (sf.contains(filter) == false) {
			sf.add(filter);
		}
	}

	public static boolean delFilter(SerializeFilter filter) {
		return sf.remove(filter);
	}

	public static String toJson(Object obj) {
		return JSON.toJSONString(obj, sf.toArray(new SerializeFilter[sf.size()]));
	}

	public static <T> T toObject(String json, Class<T> cls) {
		return JSON.parseObject(json, cls);
	}

	public static <T> List<T> toArray(String json, Class<T> cls) {
		return JSON.parseArray(json, cls);
	}

	public static <T> T toType(String json, TypeReference<T> tr) {
		return JSON.parseObject(json, tr);
	}
}
